package com.billdowney.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import com.billdowney.entity.user.UserLoginInfo;
import com.billdowney.entity.user.UserLoginRecordStatus;
import com.billdowney.security.SecurityConst;
import com.billdowney.service.interfaces.user.UserLoginRecordService;
import com.billdowney.util.CommonUtil;
import com.billdowney.util.DateUtil;

/**
 * @ClassName: ContentListener
 * @Description: 项目内容监听
 * @author 超级小富翁 - BillDowney
 * @date 2018年8月30日 下午11:32:59
 */
@Component
public class ContentListener extends ContextLoader implements ServletContextListener, HttpSessionListener {

	private Logger logger = LoggerFactory.getLogger(ContentListener.class);
	@Autowired
	private UserLoginRecordService userLoginRecordService;

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		logger.info(arg0.getSession().getId() + "，用户访问：" + DateUtil.getCurrentDate());
		// 添加SessionContext工具中的值
		// SessionContextUtil.addHttpSession(arg0.getSession().getId(), arg0.getSession());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		logger.info(arg0.getSession().getId() + "，用户退出访问：" + DateUtil.getCurrentDate());
		// 删除SessionContext工具中的值
		// SessionContextUtil.delHttpSession(arg0.getSession().getId());
		Object securityContextObj = arg0.getSession().getAttribute(SecurityConst.SESSION_KEY);
		if (CommonUtil.isNotEmpty(securityContextObj)) {
			if (securityContextObj instanceof SecurityContextImpl) {
				SecurityContextImpl securityContext = (SecurityContextImpl) securityContextObj;
				userLoginRecordService.addUserLoginRecord(arg0.getSession(),
						(UserLoginInfo) securityContext.getAuthentication().getPrincipal(),
						UserLoginRecordStatus.loginOvertime);
			}
		}
	}

	// 关闭项目执行的方法
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.info(arg0.getServletContext().getContextPath() + " 项目关闭--" + DateUtil.getCurrentDate());
	}

	// 开启项目执行的方法
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		logger.info(arg0.getServletContext().getContextPath() + " 项目开启--" + DateUtil.getCurrentDate());
	}

}
